/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;


import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;

import scheduler.databean.Course;
import scheduler.formbean.searchForm;
import scheduler.model.CourseDao;
import scheduler.model.SectionDao;
import scheduler.model.Model;

public class SearchCoursesAction extends Action {

	private static FormBeanFactory<searchForm> formBeanFactory =
		FormBeanFactory.getInstance(searchForm.class,"<>\"");
	private CourseDao courseDao;
	private SectionDao sectionDao;
	
	public SearchCoursesAction(Model model) {
		
		courseDao = model.getCourseDao();
		sectionDao=model.getSectionDao();
	}

	public String getName() { return "search-courses.do"; }
    
    public String perform(HttpServletRequest request) {   	
    	Course[] result1;
    	Course[] result2;
    	searchForm form = formBeanFactory.create(request);
		
		
		 if (!form.isPresent()) {
	            return "search-courses.jsp";
	        }
		 request.setAttribute("form",form);
		try {
			System.out.println(form.getNumber());
			 result1=courseDao.getSearch(form);
			 result2=courseDao.getCoursesBySections(sectionDao.getSearch(form));
			
			
			 request.setAttribute("result", MergeResult(result1, result2, form));
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
    	return "search-courses.jsp";
    }
    
    private Course[] MergeResult(Course[] a, Course[] b, searchForm form)
    {
    	ArrayList<Course> merged= new ArrayList<Course>();
    	
    	if(form.isCourse() && form.isSection())
    	{
    		for(int i=0; i<a.length ;i++)
    		{
    			for(int x=0; x<b.length; x++)
    			{
    				if(a[i].getId()== b[x].getId())
    				{
    					merged.add(a[i]);
    				}
    			}
    		}
    	}
    	else if(form.isCourse())
    	{
    		return a;
    	}
    	else if(form.isSection())
    	{
    		return b;
    	}
    	
    	Course[] coursearray= new Course[merged.size()];
    	for(int i=0; i<merged.size(); i++)
    	{
    		coursearray[i]=merged.get(i);
    	}
    	return coursearray;
    	
   
    	
    }
}
